import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/mode/list_pagination_model.dart';
import 'package:flutter_smart_heating/pages/information/station/view/status.dart';
import 'package:flutter_smart_heating/ui/src/slide_panel.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:get/get.dart';
import 'package:horizontal_data_table/horizontal_data_table.dart';

import '../widget/filter.dart';

class InformationStationActualPage extends StatefulWidget {
  const InformationStationActualPage({super.key});

  @override
  State<InformationStationActualPage> createState() =>
      _InformationStationActualPageState();
}

class _InformationStationActualPageState
    extends State<InformationStationActualPage>
    with SingleTickerProviderStateMixin {
  late TabController tabController;

  ListPaginationModel pagination = ListPaginationModel();
  HDTRefreshController refreshController = HDTRefreshController();
  List<dynamic> list = [];
  List<double> colunmWidths = [100, 80, 80, 80, 80, 80, 80, 80, 80];
  List<double> spanOneArr = [];
  List<double> spanTwoArr = [];
  List<bool> spanColor = [];
  int tabIndex = 0;
  ValueNotifier loading = ValueNotifier<bool>(true);
  ValueNotifier hasFilter = ValueNotifier<bool>(false);
  PanelController? panelController;
  Map<String, dynamic> filterParams = {};
  @override
  void initState() {
    super.initState();

    calcColunmWidth();

    tabController = TabController(length: 2, vsync: this);
  }

  onPageReady() async {
    await fetchData();
  }

  Future fetchData() async {
    var res =
        await Http.instance.post('/api/information/station/actual', data: {
      'page': pagination.currentPage,
      ...filterParams,
    });
    if (res.code == 1) {
      if (pagination.currentPage <= 1) {
        list.clear();
      }
      pagination = ListPaginationModel.fromJson(res.data);
      res.data['data'].forEach(
        (item) => list.add(item),
      );
    }
    loading.value = false;
    getRowHeight();
    refreshController.refreshCompleted();
    if (pagination.hasMore) {
      refreshController.loadComplete();
    } else {
      refreshController.loadNoData();
    }

    setState(() {});
  }

  /// 计算每列宽度使之至少能充满整个屏幕，主要是针对大屏幕
  calcColunmWidth() {
    if (maxWidth < Get.size.width) {
      var add = (Get.size.width - maxWidth) / colunmWidths.length;
      for (var i = 0; i < colunmWidths.length; i++) {
        colunmWidths[i] += add;
      }
    }
  }

  /// table的最大宽度
  double get maxWidth {
    double total = 0;
    for (var i in colunmWidths) {
      total += i;
    }
    return total;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        scrolledUnderElevation: 0,
        title: UiPanel(
          width: 200,
          borderRadius: BorderRadius.circular(30),
          height: 35,
          child: TabBar(
            controller: tabController,
            isScrollable: false,
            dividerColor: Colors.transparent,
            indicatorSize: TabBarIndicatorSize.tab,
            splashBorderRadius: BorderRadius.circular(30),
            indicator: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(30),
              gradient: const LinearGradient(
                colors: [
                  Color.fromARGB(255, 11, 232, 248),
                  Color.fromARGB(255, 33, 51, 243),
                ],
              ),
            ),
            indicatorColor: Colors.black,
            labelColor: Colors.white,
            unselectedLabelColor:
                UiTheme(context).matchColor(Colors.black, Colors.white),
            unselectedLabelStyle: const TextStyle(
              fontWeight: FontWeight.normal,
            ),
            labelStyle: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: UiTheme.fontSize.tabbarFontSize,
              color: Colors.red,
            ),
            tabs: const [
              Tab(
                text: "一网数据",
              ),
              Tab(
                text: "二网数据",
              ),
            ],
            onTap: (index) {
              setState(() {
                tabIndex = index;
              });
            },
          ),
        ),
        actions: [
          IconButton(
            onPressed: () {
              if (panelController?.isPanelOpen == true) {
                panelController?.close();
              } else {
                panelController?.open();
              }
            },
            icon: ValueListenableBuilder(
              valueListenable: hasFilter,
              builder: (context, state, widget) {
                return Icon(state ? UiIcons.filter_fill : UiIcons.filter);
              },
            ),
          ),
        ],
      ),
      body: UiLifeCycle(
        onRouteDone: onPageReady,
        child: FilterView(
          filter: 'station.actual',
          onCreated: (context, controller, filter) {
            hasFilter.value = filter.state;
            panelController = controller;
          },
          onChange: (filter) {
            hasFilter.value = filter.state;
            loading.value = true;
            filterParams = filter.params;
            pagination.currentPage = 1;
            fetchData();
          },
          body: Stack(
            children: [
              Padding(
                padding: const EdgeInsets.only(top: UiTheme.toolbarSpacing),
                child: HorizontalDataTable(
                  leftHandSideColumnWidth: colunmWidths.first,
                  rightHandSideColumnWidth: maxWidth - colunmWidths.first,
                  isFixedHeader: true,
                  headerWidgets: _getTitleWidget(),
                  leftSideItemBuilder: _generateFirstColumnRow,
                  rightSideItemBuilder: cellColumnRow,
                  itemCount: list.length,
                  // rowSeparatorWidget: Divider(
                  //   color: Colors.grey.withOpacity(0.5),
                  //   height: 0,
                  //   thickness: 0,
                  // ),
                  elevationColor: Colors.grey.withOpacity(0.5),
                  elevation: list.isEmpty ? 0 : 1,
                  loadIndicator: const ClassicFooter(
                    idleText: '上拉加载',
                    noDataText: "加载完毕",
                    loadingText: '正在加载',
                    canLoadingText: '释放加载',
                    loadingIcon: SizedBox(
                      width: 16,
                      height: 16,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        color: Colors.grey,
                      ),
                    ),
                  ),
                  htdRefreshController: refreshController,
                  enablePullToRefresh: list.isNotEmpty,
                  refreshIndicator: const ClassicHeader(
                    refreshingIcon: SizedBox(
                      width: 16,
                      height: 16,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        color: Colors.grey,
                      ),
                    ),
                    releaseIcon: Icon(Icons.arrow_upward, color: Colors.grey),
                    idleText: "下拉刷新",
                    releaseText: '释放刷新',
                    refreshingText: '正在刷新',
                    completeText: '刷新成功',
                  ),
                  onRefresh: () {
                    pagination.currentPage = 1;
                    fetchData();
                  },
                  onLoad: () {
                    pagination.currentPage++;
                    fetchData();
                  },
                  enablePullToLoadNewData: list.isNotEmpty,
                  leftHandSideColBackgroundColor: Colors.transparent,
                  rightHandSideColBackgroundColor: Colors.transparent,
                ),
              ),
              ValueListenableBuilder(
                valueListenable: loading,
                builder: (context, state, widget) {
                  if (state) {
                    return const Align(child: UiLoading());
                  } else if (list.isEmpty) {
                    return const Align(child: UiResult());
                  } else {
                    return const SizedBox.shrink();
                  }
                },
              )
            ],
          ),
        ),
      ),
    );
  }

  List<Widget> _getTitleWidget() {
    String name = tabIndex == 0 ? '一' : '二';
    return [
      _getTitleItemWidget('热站名称', colunmWidths[0], 0),
      _getTitleItemWidget('分区', colunmWidths[1], 1),
      _getTitleItemWidget('$name网供温', colunmWidths[2], 2),
      _getTitleItemWidget('$name网回温', colunmWidths[3], 3),
      _getTitleItemWidget('供回温差', colunmWidths[4], 4),
      _getTitleItemWidget('$name网供压', colunmWidths[2], 2),
      _getTitleItemWidget('$name网回压', colunmWidths[3], 3),
      _getTitleItemWidget('供回压差', colunmWidths[4], 4),
      _getTitleItemWidget('设备状态', colunmWidths[4], 5),
    ];
  }

  Widget _getTitleItemWidget(String label, double width, index) {
    return Container(
      width: width,
      height: 40,
      color: Colors.grey.withOpacity(0.1),
      alignment: Alignment.center,
      child: Row(
        children: [
          cellBorder(),
          Expanded(
            child: Text(
              label,
              textAlign: TextAlign.center,
              style: const TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ],
      ),
    );
  }

  getRowHeight() {
    spanOneArr = [];
    spanTwoArr = [];
    spanColor = [];
    int concatTwo = 0;

    for (var index = 0; index < list.length; index++) {
      var item = list[index];
      if (index == 0) {
        spanOneArr.add(1);
        spanTwoArr.add(1);
      } else {
        spanOneArr.add(1);
        if (item['station_id'] == list[index - 1]['station_id']) {
          spanTwoArr.add(0);
          spanTwoArr[concatTwo] += 1;
        } else {
          concatTwo = index;
          spanTwoArr.add(1);
        }
      }
    }
    int columnIndex = 0;
    for (var index = 0; index < list.length; index++) {
      if (spanTwoArr[index] > 0) {
        columnIndex++;
        spanColor.add(columnIndex % 2 == 0);
      } else {
        spanColor.add(false);
      }
    }
  }

  Widget _generateFirstColumnRow(BuildContext context, int index) {
    return spanTwoArr[index] > 0
        ? UiTap(
            onTap: () {
              StationStatusView.show(context, id: list[index]['station_id']);
            },
            child: Container(
              width: colunmWidths.first,
              decoration: BoxDecoration(
                color: spanColor[index]
                    ? Colors.grey.withOpacity(0.1)
                    : Colors.grey.withOpacity(0),
              ),
              height: spanTwoArr[index] * 40,
              padding: const EdgeInsets.symmetric(horizontal: 5),
              alignment: Alignment.center,
              child: Text(
                list[index]['station_name'],
                textAlign: TextAlign.center,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          )
        : const SizedBox.shrink();
  }

  Widget cellColumnRow(BuildContext context, int index) {
    var item = list[index];
    Map<int, List<String>> map = {
      0: ['1', '2', '1_2', '3', '4', '3_4'],
      1: ['7', '8', '7_8', '9', '10', '9_10'],
    };
    return UiTap(
      onTap: () {
        StationStatusView.show(context, id: list[index]['station_id']);
      },
      child: Container(
        color:
            index % 2 != 0 ? Colors.grey.withOpacity(0.1) : Colors.transparent,
        height: 40,
        child: Row(
          children: [
            cellBorder(),
            Container(
              width: colunmWidths[1],
              alignment: Alignment.center,
              child: Text('${item['second_net']}'),
            ),
            for (var i = 0; i < map[tabIndex]!.length; i++)
              Row(
                children: [
                  cellBorder(),
                  Container(
                    width: colunmWidths[4],
                    alignment: Alignment.center,
                    child: Text('${item['param_${map[tabIndex]?[i]}']}'),
                  ),
                ],
              ),
            cellBorder(),
            Container(
              width: colunmWidths[4],
              alignment: Alignment.center,
              child: Text(
                '${item['status_name']}',
                style: TextStyle(
                  color: item['status'] == 'online'
                      ? Colors.green
                      : item['status'] == 'abnormal'
                          ? Colors.orangeAccent
                          : Colors.red,
                ),
              ),
            ),
            cellBorder(),
          ],
        ),
      ),
    );
  }

  Widget cellBorder() {
    return VerticalDivider(
      color: Colors.grey.withOpacity(0.5),
      width: 0,
      thickness: UiTheme.of(context).match(light: 0.2, dark: 0.1),
    );
  }
}
